package com._5704.website.controller;


import com._5704.website.exception.WebsiteException;
import com._5704.website.exception.WebsiteExceptionEnum;
import com._5704.website.util.EmailUtil;
import com._5704.website.vo.JsonVO;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Yiyoung
 * @since 2021-07-25
 */
@RestController
@RequestMapping
@Log4j2
public class UtilController {

    @Value("${download.filePath}")
    private String path;


    @GetMapping("/download")
    public void download(@RequestParam String name, HttpServletResponse response){

        String filePath = path+name;

        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(filePath);

            String filename = new File(filePath).getName();

            response.setContentType("multipart/form-data");

            response.setHeader("Content-Disposition", "attachment; fileName="+  filename +";filename*=utf-8''"+ URLEncoder.encode(filename, StandardCharsets.UTF_8));

            ServletOutputStream outputStream = response.getOutputStream();

            byte[] b = new byte[1024];

            int len;
            //从输入流中读取一定数量的字节，并将其存储在缓冲区字节数组中，读到末尾返回-1
            while ((len = inputStream.read(b)) > 0) {
                outputStream.write(b, 0, len);
            }
            inputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
            throw new WebsiteException(WebsiteExceptionEnum.FILE_READER_ERROR);
        }
    }



}
